﻿using System;
using System.Collections.Generic;
using System.Text;
using Core.Model;
using Core.Model.Links;
using Core.Parser.ASN1Parser.Nodes;
using Core.Exceptions;

namespace Core.Parser.ASN1Parser.Builders
{
    internal class LinkBuilder
    {
        internal static Link Build(TaggedNode node, Group group)
        {
            var link = new Link();
            IngredientBuilder.Build(node, link, group);

            TaggedNode e;

            if ((e = node[ASN1ContextCodes.C_LINK_CONDITION]) != null)
                link.LinkCondition = BuildLinkCondition(e, group);
            else
                throw new OpenMhegException("Link Condition not Optional");

            if ((e = node[ASN1ContextCodes.C_LINK_EFFECT]) != null)
                link.LinkEffect = ActionBuilder.Build(e, group);
            else
                throw new OpenMhegException("Link Effect not Optional");

            return link;
        }

        private static LinkCondition BuildLinkCondition(TaggedNode node, Group group)
        {
            var linkCondition = new LinkCondition();

            TaggedNode e;

            if (node.Size < 2)
                throw new OpenMhegException("Missing data");
            //if ((e = node[ASN1ContextCodes.P_EVENT_SOURCE]) != null)
                linkCondition.EventSource = ObjectRefBuilder.Build(node.First, group);
            //else
              //  throw new OpenMhegException("Event Source not Optional");

            //if ((e = node[ASN1ContextCodes.P_EVENT_TYPE]) != null)
                linkCondition.EventType = Core.Model.Events.Event.getEvent(node.Second.EnumValue);
            //else
              //  throw new OpenMhegException("Event Type not Optional");

            //if ((e = node[ASN1ContextCodes.P_EVENT_DATA]) != null)
            if (node.Size > 2)
            {
                ASN1Node t = node.Third;

                if (t is BoolNode)
                    linkCondition.EventData = t.BoolValue;
                else if ( t is IntNode)
                    linkCondition.EventData = t.IntValue;
                else if ( t is OctetStringNode)
                    linkCondition.EventData = t.StringValue;
                else
                    throw new OpenMhegException("Could not decode linkCondition.Eventdata");

            }

            return linkCondition;
        }
    }
}
